import { useState, useMemo } from 'react';
import Taro, { getStorageSync, useDidShow, useLoad, useUnload } from '@tarojs/taro';
import { demandListStore } from '@/business/store/demand/demandList';
import { cityTreeListStore } from '@/business/store/city/city';
import { userCityTreeListStore } from '@/business/store/city/userCity';
import { View, Image } from '@tarojs/components';
import { AtTabs, AtTabsPane, AtActionSheet, AtActionSheetItem } from 'taro-ui';
import Navigation from '@/components/Navigation';
import MainCard from '@/components/MainCard';
import SafePhoneModal from '@/components/SafePhoneModal';
import ChildrenTabs from '@/components/ChildrenTabs';
import ScrollList from '@/components/ScrollList';
import EmptyPage from '@/components/EmptyPage';
import SearchBox from './components/SearchBox';
import Activation from './components/Activation';
import { getMyPageUserInfo, getUserVipInfo } from '@/business/services/user/userInfo';
import { fetchAddressByLocation } from '@/business/services/common/common';
import { useUserStore } from '@/business/store/user/login';
import { fetchDemandPostType, fetchDemandPostTypeAll } from '@/business/services/demand/demand';
// import { initSdk } from '@/utils/im';
// import { initUser } from '@/business/services/im';
import cssModule from './index.module.scss';
import { findCity, flatCities, getLocationIds } from '@/utils/city';
import { initSdk } from '@/utils/im';
import { dCityTreeListStore } from '@/business/store/city/dCity';
import IconFont from '@/assets/Iconfont';
import './index.scss'
import LoginTip from './components/LoginTip';
import PersonCompleteTip from './components/personCompleteTip';

/**
 * @description 需求广场
 * @author Shawn
 */

export default function Index() {
  const useUser = useUserStore();

  const { userInfo } = useUserStore();

  console.log('userInfo === ', userInfo);



  const router = Taro.getCurrentInstance().router;

  // const [isRender, setRender] = useState(false)

  const [current, setCurrent] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);

  const [tabs, setTabs] = useState<any[]>([]);

  const [orderField, setOrderField] = useState('recommend');

  const childrenTabs = useMemo(() => [
    {
      name: '推荐',
      value: 'recommend',
    },
    {
      name: '最新',
      value: 'newest',
    },
    {
      name: '点赞最多',
      value: 'likeMost',
    },
    {
      name: '收藏最多',
      value: 'collectMost',
    }], []);

  const [cityCode, setCityCode] = useState('');
  const [location, setLocation] = useState('');
  const [locationIds, setLocationIds] = useState({
    provinceId: '',
    cityId: '',
    districtId: '',
  })

  const demandList = demandListStore((state) => state.demandList);
  const isDataLoaded = demandListStore((state) => state.isDataLoaded);
  const hasMore = demandListStore((state) => state.hasMore);

  // 获取当前城市
  const getLocation = async (title: any) => {
    const res = await Taro.getLocation({
      type: 'gcj02',
      isHighAccuracy: true,
    });
    const { latitude, longitude } = res;
    if (!latitude || !longitude) {
      getDemandList(
        title,
        orderField,
      );
    } else {
      const location = await fetchAddressByLocation({
        latitude: latitude,
        longitude: longitude
      });
      setLocation(location);
      console.log('location data === ', location);

      const code = findCity(flatCities(cityTreeListStore.getState().cityTreeList), location.data.adcode)
      setCityCode(code);
      getDemandList(
        title,
        orderField,
        code,
      );

      const { provinceId, cityId, districtId } = getLocationIds(flatCities(cityTreeListStore.getState().cityTreeList), code)
      setLocationIds({
        provinceId,
        cityId,
        districtId,
      })
    }
  }

  useDidShow(() => {
    initSdk()
    updateIndex()
  })

  // 获取需求列表
  const getDemandList = async (tag?: string, orderField?: string, cityCode?: string) => {
    setCurrentPage(1);
    if (tag === '全部') tag = '';
    await demandListStore.getState().getDemandList({ current: 1, size: 10 }, tag, orderField, cityCode);
  };

  // 获取需求类型列表
  const getDemandPostTypeList = async (isLocation = true) => {
    const res = await fetchDemandPostTypeAll({})
    if (res.success) {
      const list = [...res.data.followedList.map(item => ({ title: item.title })), ...res.data.unFollowedList.map(item => ({ title: item.title.length > 5 ? item.title.slice(0, 5) + '...' : item.title.length }))]

      list.unshift({ title: '全部' })
      setTabs(list)
      if (isLocation) {
        getLocation(
          list[0].title,
        );
      }
    }
  }

  const updateIndex = async () => {
    const update = Taro.getStorageSync('indexUpdate')
    if (update) {
      setCurrent(0)
      setCurrentPage(10)
      setOrderField('recommend')
      await getDemandPostTypeList(false)
      await getDemandList('', '', cityCode)
      Taro.removeStorageSync('indexUpdate')
    }
  }

  // 上拉加载
  const handleOnScrollToLower = async () => {
    if (!hasMore) return;
    const nextPage = currentPage + 1;
    setCurrentPage(nextPage);
    let tag = tabs[current].title;
    if (tag === '全部') tag = '';
    await demandListStore.getState().handlePullUpOrDown({ current: nextPage, size: 10 }, tag, orderField, cityCode);
  };


  // 选项卡切换
  const handleClickTab = (current: any) => {
    setCurrentPage(1);
    setCurrent(current);
    const tag = tabs[current].title;
    getDemandList(tag, orderField, cityCode);
  };

  // 子选项卡切换
  const handleTabChange = (tabValue: string) => {
    setCurrentPage(1);
    setOrderField(tabValue);
    const tag = tabs[current].title;
    const orderField = tabValue;
    getDemandList(tag, orderField, cityCode);
  }

  // 子选项卡地区切换
  const handleTabRegionChange = (regionId: string) => {
    setCurrentPage(1);
    setCityCode(regionId);
    const tag = tabs[current].title;
    getDemandList(tag, orderField, regionId);
  };

  // 去搜索
  const handleSearch = () => {
    Taro.navigateTo({
      url: `/subPackages/search/index`,
    });
  };

  // 去发布
  const handlePublish = () => {
    if (useUser?.vipInfo?.vipLevelId !== '001') {
      Taro.navigateTo({
        url: '/subPackages/equity/index'
      })
      return
    }
    Taro.navigateTo({
      url: `/subPackages/publish/index`,
    });
  };

  // 开通VIP
  const handleOpenVip = () => {
    Taro.navigateTo({
      url: `/subPackages/equity/index`,
    });
  };

  // 浮动按钮拖拽相关
  const [btnPos, setBtnPos] = useState({ right: 20, bottom: 40 });
  const [dragging, setDragging] = useState(false);
  const [offset, setOffset] = useState({ x: 0, y: 0 });
  const [windowSize] = useState(() => {
    const { windowWidth, windowHeight } = Taro.getSystemInfoSync();
    return { windowWidth, windowHeight };
  });

  // 拖拽开始
  const handleTouchStart = (e: any) => {
    setDragging(true);
    const touch = e.touches[0];
    setOffset({
      x: windowSize.windowWidth - btnPos.right - touch.clientX,
      y: windowSize.windowHeight - btnPos.bottom - touch.clientY,
    });
  };

  // 拖拽中
  const handleTouchMove = (e: any) => {
    if (!dragging) return;
    const touch = e.touches[0];
    let right = windowSize.windowWidth - touch.clientX - offset.x;
    let bottom = windowSize.windowHeight - touch.clientY - offset.y;

    // 限制拖拽范围
    right = Math.max(0, Math.min(right, windowSize.windowWidth - 60));
    bottom = Math.max(0, Math.min(bottom, windowSize.windowHeight - 60));

    setBtnPos({ right, bottom });
  };

  // 拖拽结束
  const handleTouchEnd = () => {
    setDragging(false);
  };

  // 获取城市数据
  const getCityTreeList = async () => {
    await cityTreeListStore.getState().getCityTreeList();
  }

  // 获取城市数据
  const getUserCityTreeList = async () => {
    await userCityTreeListStore.getState().getUserCityTreeList();
  }

  // 获取我的用户信息
  const getMyUserInfo = async () => {
    const res = await getMyPageUserInfo()
    if (res.success) {
      useUser.setUserInfo(res.data as any)
    }
    const vip = await getUserVipInfo()
    if (vip.success) {
      useUser.setUserVip(vip.data)
    }
  }

  useUnload(() => {
    console.log('App is unloading');
  });

  // 安全号弹窗
  const [isSafePhoneModalOpened, setIsSafePhoneModalOpened] = useState(false);

  // 联系弹窗
  const [isActionSheetOpened, setIsActionSheetOpened] = useState(false);

  // 拨打电话
  const handleCall = () => {
    setIsActionSheetOpened(false);
    // setIsSafePhoneModalOpened(true);
    Taro.makePhoneCall({
      phoneNumber: contactMobile,
      success: () => {
      },
      fail: (err) => {
        console.error('拨打电话失败:', err)
        Taro.showToast({
          title: '拨打失败',
          icon: 'none'
        })
      }
    })
  };

  // 发送消息
  const handleSendMsg = () => {
    setIsActionSheetOpened(false);
    if (!contactUserID) return
    Taro.navigateTo({
      url: '/subPackages/chatlist/index' + `?conversationID=C2C${contactUserID}`
    })
  };

  const [contactMobile, setContactMobile] = useState(''); // 联系电话
  const [contactUserID, setContactUserID] = useState(''); // 用户userID
  const [showPhone, setShowPhone] = useState(true); // 是否显示拨打电话选项
  // 联系TA
  const handleContact = (item: any) => {
    console.log('useUser.userInfo === ', item);
    if (useUser?.vipInfo?.vipLevelId !== '001') {
      Taro.navigateTo({
        url: '/subPackages/equity/index'
      })
      return
    }
    console.log('contact item === ', item);
    // setShowPhone(item.phonePrivacyBool); // 如果对方设置了隐私号，则不显示拨打电话选项
    setContactMobile(item.userSimpleVO.contactMobile);
    setContactUserID(item?.userSimpleVO.imUserSig)
    setIsActionSheetOpened(true);
    setShowPhone(item.virtualNumberIsEnable ?? false)
  };

  useLoad(async () => {
    const inviteCellphone = router?.params?.inviteCellphone || '';
    Taro.setStorageSync('inviteCellphone', inviteCellphone)
    await getCityTreeList()
    getDemandPostTypeList()

    getUserCityTreeList()
    dCityTreeListStore.getState().getdCityTreeList()
    const isLogin = Taro.getStorageSync('isLogin');
    if (isLogin) {
      await getMyUserInfo()
    }
  })

  const toCateGory = () => {
    Taro.navigateTo({
      url: '/subPackages/category/index'
    })
  }

  const handleLogin = () => {
    Taro.navigateTo({
      url: '/pages/login/index'
    })
  }

  const handleComplete = () => {
    Taro.navigateTo({
      url: '/subPackages/person/index'
    })
  }

  const isLogin = getStorageSync(
    'isLogin'
  )

  return (
    <View>
      {/* 自定义导航栏 */}
      <Navigation title='需求广场' />

      {/* 页面主体内容 */}
      <View className={cssModule.container}>
        {/* vip开通 */}
        {isLogin && (useUser?.vipInfo?.vipLevelId && useUser?.vipInfo?.vipLevelId !== '001' && !useUser.userInfo.baoZhiHao) && <View className={cssModule.activation}>
          <Activation clickBtn={handleOpenVip} />
        </View>}

        {
          !isLogin && <View className={cssModule.activation}>
            <LoginTip clickBtn={handleLogin} isShowBtn />
          </View>
        }

        {
          (isLogin && userInfo.dataCompletion !== 100) && <View className={cssModule.activation}>
            <PersonCompleteTip clickBtn={handleComplete} isShowBtn />
          </View>
        }

        <View className={cssModule.listBox}>
          {/* 搜索组件 */}
          <View className={cssModule.searchBox} onClick={handleSearch}>
            <SearchBox />
          </View>

          {/* 选项卡组件 */}
          <View className={`${cssModule.tabsBox} index-tabs-box`}>
            <AtTabs
              current={current}
              tabList={tabs.map((item) => ({ title: item.title }))}
              onClick={handleClickTab}
              swipeable={false}
              scroll={tabs.length > 5}
            >
              {tabs.map((item: any, index: number) => (
                <AtTabsPane current={current} index={index} key={item.title}>
                  <View className={cssModule.tabContent}>
                    {/* 子选项卡组件 */}
                    <View className={cssModule.childrenTabs}>
                      <ChildrenTabs childrenTabs={childrenTabs} location={location} locationIds={locationIds} onTabChange={handleTabChange} onRegionChange={handleTabRegionChange} />
                    </View>
                    {/* 列表容器组件 */}
                    <View className={`${cssModule.scrollList} ${!isLogin ? cssModule.scrollList646 : ''} ${isLogin && (useUser?.vipInfo?.vipLevelId && useUser?.vipInfo?.vipLevelId !== '001' && !useUser.userInfo.baoZhiHao) && userInfo.dataCompletion === 100 ? cssModule.scrollList646 : ''} ${isLogin && !(useUser?.vipInfo?.vipLevelId && useUser?.vipInfo?.vipLevelId !== '001' && !useUser.userInfo.baoZhiHao) && userInfo.dataCompletion !== 100 ? cssModule.scrollList646 : ''} ${isLogin && !(useUser?.vipInfo?.vipLevelId && useUser?.vipInfo?.vipLevelId !== '001' && !useUser.userInfo.baoZhiHao) && userInfo.dataCompletion !== 100 ? cssModule.scrollList802 : ''}`}>

                      <ScrollList childrenNode={
                        <>
                          {
                            (!isDataLoaded && (!demandList || demandList.length === 0)) ? (
                              <EmptyPage defaultName='' />
                            ) : (
                              demandList?.map((item: any, idx: number) => (
                                <View className={cssModule.listViewCard} key={item.id ?? idx}>
                                  <MainCard item={item} cityCode={cityCode} onContact={handleContact} isOprate />
                                </View>
                              ))
                            )
                          }
                        </>
                      }
                        height={`100%`}
                        onScrollToLower={handleOnScrollToLower}
                        hasMore={hasMore}
                        isDataLoaded={isDataLoaded}
                      />
                    </View>
                  </View>
                </AtTabsPane>
              ))}
            </AtTabs>
            <View className={cssModule.categoryTab} onClick={toCateGory}>
              <IconFont name='category' size={44} />
            </View>
          </View>
        </View>
      </View>

      {/* 安全号弹窗 */}
      <SafePhoneModal
        contactMobile={contactMobile}
        isOpened={isSafePhoneModalOpened}
        onClose={() => setIsSafePhoneModalOpened(false)}
      />
      {/* 联系TA */}
      <AtActionSheet
        isOpened={isActionSheetOpened}
        cancelText='取消'
        onClose={() => setIsActionSheetOpened(false)}
        onCancel={() => setIsActionSheetOpened(false)}
      >
        {
          showPhone &&
          <AtActionSheetItem onClick={handleCall}>拨打对方电话</AtActionSheetItem>
        }
        <AtActionSheetItem onClick={handleSendMsg}>发送消息</AtActionSheetItem>
      </AtActionSheet>

      {/* 可拖拽浮动按钮 */}
      <View
        className={cssModule.publish}
        style={{
          position: 'fixed',
          right: btnPos.right,
          bottom: btnPos.bottom,
          zIndex: 9999,
          cursor: dragging ? 'grabbing' : 'grab',
          touchAction: 'none',
        }}
        onClick={handlePublish}
        onTouchStart={handleTouchStart}
        onTouchMove={handleTouchMove}
        onTouchEnd={handleTouchEnd}
        catchMove
      >
        <Image src='https://baoyouqun.cn/files/static/images/publish.png' mode='aspectFill' />
      </View>
    </View>
  );
}
